package com.komorebi.friends.controller;

import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.komorebi.friends.common.BaseResponse;
import com.komorebi.friends.common.ErrorCode;
import com.komorebi.friends.common.ResultUtils;
import com.komorebi.friends.exception.BusinessException;
import com.komorebi.friends.model.dto.team.*;
import com.komorebi.friends.model.entity.Team;
import com.komorebi.friends.model.entity.User;
import com.komorebi.friends.model.vo.TeamUserVO;
import com.komorebi.friends.model.vo.TeamVO;
import com.komorebi.friends.service.TeamService;
import com.komorebi.friends.service.UserService;
import com.komorebi.friends.service.UserTeamService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/team")
public class TeamController {
    @Autowired
    private TeamService teamService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserTeamService userTeamService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/add")
    public BaseResponse<Long> addTeam(@RequestBody TeamAddRequest teamAddRequest, HttpServletRequest request) {
        if(teamAddRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = new Team();
        BeanUtils.copyProperties(teamAddRequest,team);
        User loginUser = userService.getLoginUser(request);
        Long teamId = teamService.addTeam(team,loginUser);
        return ResultUtils.success(teamId);  // 这个时候队伍id已经生成了，直接返回给前端
    }

    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteTeam(@RequestBody TeamDeleteRequest teamDeleteRequest,HttpServletRequest request) {
        if(teamDeleteRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean delete = teamService.deleteTeam(teamDeleteRequest,loginUser);
        if(!delete){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"删除队伍失败");
        }
        return ResultUtils.success(true);
    }

    @PostMapping("/update")
    public BaseResponse<Boolean> updateTeam(@RequestBody TeamUpdateRequest teamUpdateRequest,HttpServletRequest request){
        if(teamUpdateRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean result = teamService.updateTeam(teamUpdateRequest,loginUser);
        if(!result){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"更新队伍失败");
        }
        return ResultUtils.success(true);
    }

    @GetMapping("/get")
    public BaseResponse<Team> getTeamById(Long id){
        if(id == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = teamService.getById(id);
        if(team == null){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"队伍不存在");
        }
        log.info("get team by id: 2");
        return ResultUtils.success(team);
    }

    @GetMapping("/list")
    public BaseResponse<List<TeamUserVO>> listTeam(TeamQueryRequest TeamQueryRequest, HttpServletRequest request) {
        if(TeamQueryRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //需要知道是否是管理员，如果是管理员，可以查看私有的队伍信息
        boolean admin = userService.isAdmin(request);
        List<TeamUserVO> teams = teamService.listTeam(TeamQueryRequest,admin);
        return ResultUtils.success(teams);
    }

    @GetMapping("/list/page")
    public BaseResponse<Page<Team>> listTeamByPage(TeamQueryRequest TeamQueryRequest) {
        if(TeamQueryRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = new Team();
        BeanUtils.copyProperties(TeamQueryRequest,team);
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>(team);
        Page<Team> page = new Page<>(TeamQueryRequest.getCurrent(),TeamQueryRequest.getPageSize());
        Page<Team> teamPage = teamService.page(page, queryWrapper);
        return ResultUtils.success(teamPage);
    }

    @PostMapping("/join")
    public BaseResponse<Boolean> joinTeam(@RequestBody TeamJoinRequest teamJoinRequest, HttpServletRequest request){
        if(teamJoinRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"申请加入参数不能为空");
        }
        User loginUser = userService.getLoginUser(request);
        boolean res = teamService.joinTeam(teamJoinRequest,loginUser);
        return ResultUtils.success(BooleanUtil.isTrue(res));  //如果是true则返回 true ；如果是 false 或者 为空则返回 false
    }

    @PostMapping("/quit")
    public BaseResponse<Boolean> quitTeam(@RequestBody TeamQuitRequest teamQuitRequest, HttpServletRequest request){
        if(teamQuitRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"退出队伍传入参数为空");
        }
        User loginUser = userService.getLoginUser(request);
        boolean res = teamService.quitTeam(teamQuitRequest,loginUser);
        return ResultUtils.success(BooleanUtil.isTrue(res));
    }

    /**
     * 用户加入的队伍
     * @param request
     * @return
     */
    @GetMapping("/list/my/join")
    public BaseResponse<List<TeamUserVO>> listMyJoinTeam(TeamQueryRequest teamQueryRequest, HttpServletRequest request){
        if(teamQueryRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"队伍查询请求参数不能为空");
        }
        User loginUser = userService.getLoginUser(request);
        List<Long> teamIds = userTeamService.listTeam(loginUser.getId());
//        List<TeamVO> teamVOS = teamIds.stream().map(teamId -> {
//            Team team = teamService.getById(teamId);
//            TeamVO teamVO = new TeamVO();
//            BeanUtils.copyProperties(team, teamVO);
//            return teamVO;
//        }).collect(Collectors.toList());
        teamQueryRequest.setIdList(teamIds);
        List<TeamUserVO> teamUserVOS = teamService.listTeam(teamQueryRequest, false);
        return ResultUtils.success(teamUserVOS);
    }

    /**
     * 列出用户创建的队伍
     * @param teamQueryRequest
     * @param request
     * @return
     */
    @GetMapping("/list/my/create")
    public BaseResponse<List<TeamUserVO>> listMyCreateTeam(TeamQueryRequest teamQueryRequest,HttpServletRequest request){
        if(teamQueryRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"队伍查询请求参数不能为空");
        }
        User loginUser = userService.getLoginUser(request);
        teamQueryRequest.setUserId(loginUser.getId());
        List<TeamUserVO> teamUserVOS = teamService.listTeam(teamQueryRequest, true);
        return ResultUtils.success(teamUserVOS);
    }


}
